/*
 * Copyright (c) 2020 Carnegie Lee
 * All rights reserved
 */
package com.geekc.rabbitmq.config;

import com.geekc.rabbitmq.constant.RabbitMQConst;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * RabbitMQ配置类
 * @author Carnegie Lee
 */
@Configuration
public class RabbitMQConfig {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 主交换器
     * @return
     */
    @Bean
    public TopicExchange exchange() {
        Map<String, Object> argsMap = new HashMap<String, Object>();
        argsMap.put("alternate-exchange", RabbitMQConst.RABBITMQ_BAK_EXCHANGE_NAME);
        TopicExchange exchange = new TopicExchange(RabbitMQConst.RABBITMQ_EXCHANGE_NAME, true, false, argsMap);
        return exchange;
    }

    /**
     * 备用交换器
     * @return
     */
    @Bean
    public FanoutExchange bakExchange() {
        FanoutExchange exchange = new FanoutExchange(RabbitMQConst.RABBITMQ_BAK_EXCHANGE_NAME, true, false, null);
        return exchange;
    }

    /**
     * 死信交换器
     * @return
     */
    @Bean
    public TopicExchange dlxExchange() {
        TopicExchange exchange = new TopicExchange(RabbitMQConst.RABBITMQ_DLX_EXCHANGE_NAME, true, false);
        return exchange;
    }

    @Bean
    public RabbitAdmin rabbitAdmin() {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(rabbitTemplate);
        // 声明主交换器
        rabbitAdmin.declareExchange(exchange());
        // 声明备用交换器
        rabbitAdmin.declareExchange(bakExchange());
        // 声明死信交换器
        rabbitAdmin.declareExchange(dlxExchange());
        return rabbitAdmin;
    }
}
